﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;

namespace DiskFileUpload
{
    // 使用 HttpWorkerRequest 的实现
    public class HttpWorkderFileUpload : IFileUpload
    {
        private HttpWorkerRequest worker;
        private long length;
        private long position;
        private int preloadLength;
        private Encoding bodyEncoding;

        private NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        public HttpWorkderFileUpload(System.Web.HttpWorkerRequest worker, System.Text.Encoding encoding )
        {
            // 取得编码的类型
            this.bodyEncoding = encoding;
            this.worker = worker;
            this.length = worker.GetTotalEntityBodyLength();
            this.preloadLength = worker.GetPreloadedEntityBodyLength();
            this.position = this.preloadLength;
        }

        #region IFileUpload Members

        public long Length
        {
            get { return this.length;  }
        }

        public int Read(byte[] buffer, int offset, int count)
        {
            int numBytesToRead = this.worker.ReadEntityBody(buffer, offset, count);
            this.position += numBytesToRead;

            this.logger.Trace("Length: {0},  Position: {1}, Percent: {2}",
                this.length,
                this.position,
                this.position * 100 / this.length
                );

            // 通过事件报告数据读取的进度
            HttpWorkerFileUploadEventArgs e = new HttpWorkerFileUploadEventArgs();
            e.Length = this.length;
            e.Position = this.position;

            this.OnReadComplete(e);

            return numBytesToRead;
        }

        public int PreloadLength
        {
            get { return this.preloadLength; }
        }

        public int GetPreloadedBody(byte[] buffer, int offset)
        {
            return this.worker.GetPreloadedEntityBody(buffer, offset);
        }

        public byte[] GetPreloadedBody()
        {
            return this.worker.GetPreloadedEntityBody();
        }


        public Encoding  Encoding
        {
            get { return this.bodyEncoding; }
        }

        public long Position
        {
            get
            {
                return this.position;
            }
        }

        public event HttpWorkerFileUploadHandler ReadComplete;

        protected void OnReadComplete( HttpWorkerFileUploadEventArgs e)
        {
            if (this.ReadComplete != null)
            {
                this.ReadComplete(this, e);
            }
        }

        #endregion
    }
}
